package lt.ntec.danblog.server.blog;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lt.ntec.danblog.server.blog.model.Post;
import lt.ntec.danblog.server.blog.model.PostDAO;
import lt.ntec.danblog.server.core.CoreController;
import lt.ntec.danblog.server.core.Message;
import lt.ntec.danblog.server.core.MessageManager;
import lt.ntec.danblog.server.core.Messageable;
import lt.ntec.danblog.server.core.UserManager;
import lt.ntec.danblog.server.core.validator.ValidationException;
import lt.ntec.danblog.shared.UrlPathConsts;
import com.google.inject.Inject;

public class Controller extends CoreController {

    @Inject
    private UserManager userManager;
    private static final long serialVersionUID = 5917314819729817416L;

    public Controller(HttpServletRequest req, HttpServletResponse rsp) {
        super(req, rsp);
    }

    @SuppressWarnings("unchecked")
    public void indexAction() throws IOException {
        PostDAO dao = injector.getInstance(PostDAO.class);
        List<Post> posts = (List<Post>) dao.getLastPosts();
        request.setAttribute("posts", posts);
    }

    public void newAction() throws IOException {
        if (!userManager.isAvailableValidUser()) {
            response.sendRedirect(userManager.getLoginUrl(request.getRequestURI()));
            log.info("User dispatched");
            return;
        }

        if (request.getMethod().contentEquals("POST")) {

            MessageManager manager = injector.getInstance(MessageManager.class);

            try {
                String content = request.getParameter("content");
                String tag = request.getParameter("tags");
                String title = request.getParameter("title");
                Service service = injector.getInstance(Service.class);

                service.createPost(title, content, tag);

                manager.addMessage(new Message(Messageable.Type.NOTICE,
                        "Post added"));

                response.sendRedirect(UrlPathConsts.BlogPosts);
            } catch (ValidationException e) {
                manager.addMessage(new Message(Messageable.Type.WARNING,
                        "Post data is not valid. Please review it."));
                manager.addMessages(e.getMessages());
            } catch (BlogServiceException e) {
                manager.addMessage(new Message(Messageable.Type.ERROR,
                        "Post could not be created. Contact administrator"));
            }
            return;
        }
    }

    public void viewAction() {
        PostDAO dao = injector.getInstance(PostDAO.class);
        Long id = Long.parseLong(getParam(0));
        Post post = dao.getById(id);
        request.setAttribute("post", post);
    }
}
